﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
using System.Threading;

namespace subdump
{
    class Download
    {
        public Download(string url, string destination)
        {
            Url = url;
            Destination = destination;
            Done = false;
        }
        public string Url
        {
            get; set;
        }
        public string Destination
        {
            get; set;
        }
        public bool Done
        {
            get; set;
        }
        public void DownloadAndDecompressGz()
        {
            Thread backgroundThread = new Thread(new ThreadStart(this.DownloadAndDecompressGzHelper));
            backgroundThread.Start();
        }
        private void DownloadAndDecompressGzHelper()
        {
            
            string dstFile = "";
            Stream strm = null;
            FileStream fsOut = null;
            GZipStream gzip = null;
            const int bufferSize = 4096;
            byte[] buffer = new byte[bufferSize];
            int count = 0;
            try
            {
                dstFile = Destination;
                System.Net.WebClient Client = new WebClient();
                strm = Client.OpenRead(Url);
                //fsIn = new FileStream(strPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                fsOut = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None);
                gzip = new GZipStream(strm, CompressionMode.Decompress, true);
                int read = -1;
                byte[] buff = new byte[128];
                read = gzip.Read(buff, 0, buff.Length);

                //make sure we have something to read

                while (read > 0)
                {
                    fsOut.Write(buff, 0, read);
                    read = gzip.Read(buff, 0, buff.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            finally
            {
                if (gzip != null)
                {
                    gzip.Close();
                    gzip = null;
                }
                if (fsOut != null)
                {
                    fsOut.Close();
                    fsOut = null;
                }
                if (strm != null)
                {
                    strm.Close();
                    strm = null;
                }
            }
            Done = true;
        }
    }
}
